from flask import abort
from flask import current_app, jsonify
from flask import request
from flask import session
from info import constants
from info import db
from info.models import User, News
from utils.response_code import RET
from . import news_blue
from flask import render_template

# 功能分析：收藏＆取消收藏处理
# 请求方式：post
# 请求路径：/news_collect
# 请求参数:news_id,user_id,action (操作类型，收藏or取消)
# 返回值：errno,errmsg
@news_blue.route('/news_collect', methods=['POST'])
def news_collect():
    # 获取参数
    user_id = session.get('user_id')

    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    if not user:
        return jsonify(errno=RET.DATAERR,errmsg='亲,还没登陆呢')

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 不为空判断
    if not all([news_id,action]):
        return jsonify(errno=RET.DATAERR,errmsg='请求参数不全')

    # 判断操作类型
    if not action in ['collect','cancel_collect']:
        return jsonify(errno=RET.DATAERR,errmsg='操作有误')

    # 获取新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻失败')
    # 判断该新闻是否存在
    if not news:
        return jsonify(errno=RET.DATAERR,errmsg='该新闻不存在')

    if action == 'collect':
        if not news in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    return jsonify(errno=RET.OK,errmsg='操作成功')


# 功能描述：展示新闻详情
# 请求路径：/news/<int:news_id>
# 请求方式：get
# 请求参数:news_id
# 响应值：html页面
@news_blue.route('/<int:news_id>')
def detail(news_id):

    # 判断用户是否登陆
    user_id = session.get('user_id')
    # 通过用户id获取用户对象
    user = None
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if user:
        user_info = user.to_dict()

    # 根据新闻id获取新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻失败')

    if not news:
        abort(404)

    # 获取热门新闻click
    try:
        # 按照全部新闻点击量排名
        # click_news = News.query.order_by(News.clicks.desc()).limit(5).all()
        # 按照该新闻详情所属类的点击量排名
        click_news = News.query.filter(News.category_id == news.category_id).order_by(News.clicks.desc()).limit(5).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取热门新闻失败')

    click_news_list = []
    for click_new in click_news:
        click_news_list.append(click_new.to_dict())

    # 判断是否收藏该新闻，默认False;如果客户存在，并且新闻在客户的收藏列表里
    is_collect = False
    if user and news in user.collection_news:
        is_collect = True

    data = {
        'user_info':user_info if user else '',
        'news_info':news.to_dict(),
        'click_news_list':click_news_list,
        'is_collect':is_collect
    }

    return render_template('news/detail.html',data=data)








